/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */

 (function () {
    OpenBlock.onInited(() => {
        StructField.prototype.getValue = function (data) {
            let rtype = this.type.registerType();
            let register = data.registers[rtype];
            let value = register[this.registerIndex];
            return value;
        }
        StructField.prototype.component = function () {
            if (this.type instanceof StructFieldTypeStruct) {
                return 'data-viewer-cell-struct';
            }
            return 'data-viewer-cell-base';
        }
    });
    Vue.component('data-viewer-cell-struct', {
        props: ['value', "field"],
        data() {
            if (this.field.type.isCollection()) {
                let obj = this.field.getValue(this.value);
                return {id:Object.keys(obj),name:this.field.type.elementType.name};
            } else {
                let obj = this.field.getValue(this.value);
                let registers = obj.registers;
                if (!registers) {
                    debugger
                }
                let integerR = registers.integer;
                let id = integerR[0];
                return { id ,name:this.field.type.name};
            }
        },
        template: '<a @click="$root.openDataTab(name)"><icon type="md-filing"></icon>{{name}}:{{id}}</a>'
    });
    Vue.component('data-viewer-cell-base', {
        props: ['value', "field"],
        data() {
            return {};
        },
        template: '<span>{{field.getValue(value)}}</span>'
    });
    let template;
    $.ajax({
        url: 'js/DataViewer.html',
        dataType: 'text',
        async: false,
        success(data, status, xhr) {
            template = data;
        }
    });
    Vue.component('data-viewer', {
        props: ['value', 'builder', 'beforedestroy'],
        data: function () {
            let sn = OpenBlock.Utils.makeSN()
            Vue.nextTick(function () {
                let dom = document.getElementById(sn);
                self.dom = dom;
            });

            let content = OpenBlock.DataImporter.importedData.compiled[this.value];
            let structDef = OpenBlock.DataImporter.importedData.structAST[this.value];
            return {
                sn,
                dom: null,
                content,
                structDef
            };
        },
        computed: {
        },
        methods: {
        },
        beforeDestroy() {
            if (this.beforedestroy) {
                this.beforedestroy(this.content);
            }
        },
        template
    });
})();